# -*- coding: utf-8 -*-

from onlinebrary.lib.converter.converter import AbstractConverter
from onlinebrary.lib.custompisa.pisa3 import pisaDocument
from pylons import config
    
import urllib2
import cStringIO as StringIO
import time
import md5

import logging
import os
import sys

log = logging.getLogger(__name__)

SVALKA = os.path.join(config['pylons.paths']['static_files'], 'svalka')
    
class HtmlToPdfConverter(AbstractConverter):

    def convert(self, url):
        src = urllib2.urlopen(url)

        encoding = None
        if src.headers.has_key('content-type'):
            try:
                encoding = src.headers['content-type'].split('charset=')[1]
                log.debug('For [%s] encoding was identified: %s', url, encoding)
            except Exception:
                pass
        
        #if encoding:
        #    content = unicode(src.read(), encoding, 'ignore').encode('utf-8')
        #else:
        content = src.read()
            
        html = StringIO.StringIO(content) #, encoding).encode("latin-1", "ignore"))
        
        filename = self.generate_filename("testtitle", SVALKA)
        
        resfile = open(filename, "wb")
        
        log.debug("Filename to save in %s", filename)
        
        pdf = pisaDocument(content, resfile, errout = sys.stdout, encoding=encoding)
        if pdf.err:
            log.error("Error: %s", str(pdf.err))
            #return "Error"
        resfile.close()

        return filename

        
    def generate_filename(self, title, dirname):
        filetitle = md5.new(str(time.time())).hexdigest() + '_' + title + '.pdf'
        fullfilename = os.path.join(dirname, filetitle)
        return fullfilename

'''path = url
xhtml = True
link_callback = pisaLinkLoader(url).getFileName
debug = 1

default_css = None

print "pisaDocument options:\n  src = %r\n  dest = %s\n  path = %r\n  link_callback = %r\n  xhtml = %r" % (src, dest, path, link_callback, xhtml);

# Prepare Context
c = pisaContext(
        path,
        debug = debug)
c.pathCallback = link_callback

# XXX Handle strings and files
#if type(src) in types.StringTypes:
#    src = cStringIO.StringIO(src)

# Use a default set of CSS definitions to get an expected output
if default_css is None:
        default_css = DEFAULT_CSS

# Parse and fill the story
pisaParser(src, c, default_css, xhtml)

#if 0:
#    import reportlab.pdfbase.pdfmetrics as pm
#    pm.dumpFontData()

# Avoid empty documents
if not c.story:
        c.addPara(force=True)

# Remove anchors if they do not exist (because of a bug in Reportlab)
for frag, anchor in c.anchorFrag:
    if anchor not in c.anchorName:
        frag.link = None

# Buffer PDF into memory
out = cStringIO.StringIO()

c.pageSize = (300, 400)

doc = PmlBaseDoc(
        out,
        pagesize = c.pageSize,
        author = c.meta["author"].strip(),
        subject = c.meta["subject"].strip(),
        keywords = [x.strip() for x in c.meta["keywords"].strip().split(",") if x],
        title = c.meta["title"].strip(),
        showBoundary = 0,
        allowSplitting = 1)

# XXX It is not possible to access PDF info, because it is private in canvas
# doc.info.producer = "pisa <http://www.holtwick.it>"

# Prepare templates and their frames
if c.templateList.has_key("body"):
        body = c.templateList["body"]
        del c.templateList["body"]
else:
        x, y, w, h = getBox("0.5cm 0.5cm -0.5cm -0.5cm", c.pageSize)
        body = PmlPageTemplate(
            id="body",
            frames=[
                Frame(x, y, w, h,
                    id = "body",
                    leftPadding = 0,
                    rightPadding = 0,
                    bottomPadding = 0,
                    topPadding = 0)],
        pagesize = c.pageSize)

# print body.frames

# print [body] + c.templateList.values()
doc.addPageTemplates([body] + c.templateList.values())

# Use multibuild e.g. if a TOC has to be created
if c.multiBuild:
        doc.multiBuild(c.story)
else:
        doc.build(c.story)

# Get the resulting PDF and write it to the file object
# passed from the caller
data = out.getvalue()
dest.write(data)
'''
